$(function () {
    var pagePaths = [
        'page/order',
        'page/user',
        'page/config'
    ];

    var defaultPageSize = 10;

    window.isArray = function (object) {
        return Object.prototype.toString.call(object) === '[object Array]';
    };

    window.selectPicker = function ($select, liveSearch) {
        var options = {};
        var liveSearch = (arguments.length > 1 ? arguments[1] : true);
        if (liveSearch) {
            options.liveSearch = true;
            options.liveSearchPlaceholder = '搜索列表项';
        }
        $select.selectpicker('destroy');
        $select.selectpicker(options);
        $select = $select.closest('.bootstrap-select');
        $select.addClass('form-control');
        $select.find('.dropdown-toggle').removeClass('btn-default')
                .addClass('btn-outline-light');
        $select.find('.dropdown-toggle .bs-caret').remove();
        $select.click(function (e) {
            var $target = $(e.target);
            var $button = $target.closest('.dropdown-toggle');
            var $fieldset = $target.closest('fieldset:disabled');
            if ($button.length > 0 && $fieldset.length > 0) {
                event.preventDefault();
                event.stopPropagation();
            }
        });
        $select.on('shown.bs.select', function (e) {
            var $selectPicker = $(e.currentTarget);
            var $menu = $selectPicker.find('.dropdown-menu.inner');
            var maxHeight = $menu.css('max-height');
            var $searchBox = $selectPicker.find('.bs-searchbox');
            if (!maxHeight || $searchBox.length === 0) return;
            maxHeight = parseInt(maxHeight.replace(/px/g, '')) -
                    $searchBox.height();
            maxHeight = Math.max(maxHeight, 2);
            $menu.css('max-height', maxHeight + 'px');
        });
    };

    window.datetimePicker = function ($control) {
        $control.datetimepicker({
            format: 'YYYY-MM-DD',
            minDate: new Date(2000, 0, 1),
            maxDate: new Date(2100, 11, 31),
            icons: {
                previous: 'fa fa-arrow-left',
                next: 'fa fa-arrow-right',
                today: 'far fa-calendar-check',
                clear: 'far fa-calendar-minus',
                close: 'far fa-calendar-times'
            },
            tooltips: {
                today: '今天',
                clear: '清空',
                close: '关闭',
                selectMonth: '选择月',
                prevMonth: '前一月',
                nextMonth: '后一月',
                selectYear: '选择年',
                prevYear: '前一年',
                nextYear: '后一年',
                selectDecade: '选择年代',
                prevDecade: '前一年代',
                nextDecade: '后一年代',
                selectCentury: '选择世纪',
                prevCentury: '前一世纪',
                nextCentury: '后一世纪'
            }
        });
    };

    window.readFormData = function ($form, trim) {
        var data = {};
        var array = $form.serializeArray();
        var dict = {};
        for (var i = 0, count = array.length; i < count; i++) {
            var value = array[i].value;
            var oldValue = null;
            if (typeof value === 'string' && trim) value = $.trim(value);
            if (dict[array[i].name]) {
                oldValue = data[array[i].name];
                if (window.isArray(oldValue)) {
                    oldValue.push(value);
                    value = oldValue;
                } else {
                    value = [oldValue, value];
                }
            } else {
                dict[array[i].name] = true;
            }
            data[array[i].name] = value;
        }
        return data;
    };

    window.showTableData = function (data, callback) {
        if (data.code !== 200) {
            window.showInformationAlert(3, data.message);
            return;
        }

        var result = data.data;
        var list = result.list || [];
        var html = template('table-template', {list: list});
        $('#data-list-group table tbody').html(html);
        window.showPaginationBar(result.current + 1, result.total);

        if (result.current >= result.total && result.current > 0 && list.length === 0) {
            window.showPaginationBar(result.current, result.total);
            $('#search-form [name="pageNumber"]').val(result.current - 1);
            if (callback) callback();
        }
    };

    window.showPaginationBar = function (currentPage, pageCount) {
        currentPage = Math.max(parseInt(currentPage), 1);
        pageCount = Math.max(parseInt(pageCount), 1);

        var firstPage = currentPage === 1;
        var lastPage = currentPage === pageCount;
        var pages = [];
        if (pageCount <= 5) {
            for (var i = 1; i <= pageCount; i++) {
                pages.push(i);
            }
        } else if (currentPage <= 3) {
            for (var i = 1; i <= 5; i++) {
                pages.push(i);
            }
        } else if (currentPage >= pageCount - 2) {
            for (i = pageCount - 4; i <= pageCount; i++) {
                pages.push(i);
            }
        } else {
            for (i = currentPage - 2; i <= currentPage + 2; i++) {
                pages.push(i);
            }
        }

        var html = '<ul class="pagination" data-page-count="' + pageCount + '" ' +
                'data-page="' + currentPage + '">';
        html = html + '<li class="page-item' + (firstPage ? ' disabled' : '') +
                '"><a class="page-link" href="javascript:" data-page="-1">' +
                '<i class="fa fa-angle-double-left"></i></a></li>';
        html = html + '<li class="page-item' + (firstPage ? ' disabled' : '') +
                '"><a class="page-link" href="javascript:" data-page="-2">' +
                '<i class="fa fa-angle-left"></i></a></li>';
        for (var i = 0, count = pages.length; i < count; i++) {
            var index = pages[i];
            if (index === currentPage) {
                html = html + '<li class="page-item active">' +
                        '<span class="page-link">' + index +  '</span></li>';
            } else {
                html = html + '<li class="page-item">' +
                        '<a class="page-link" href="javascript:" data-page="' +
                        index + '">' + index + '</a></li>';
            }
        }
        html = html + '<li class="page-item' + (lastPage ? ' disabled' : '') +
                '"><a class="page-link" href="javascript:" data-page="-3">' +
                '<i class="fa fa-angle-right"></i></a></li>';
        html = html + '<li class="page-item' + (lastPage ? ' disabled' : '') +
                '"><a class="page-link" href="javascript:" data-page="-4">' +
                '<i class="fa fa-angle-double-right"></i></a></li>';
        html = html + '</ul>';

        html = html + '<div class="input-group">' +
                '<div class="input-group-prepend">' +
                '<label class="input-group-text" for="page-no-select">页码</label>' +
                '</div>' +
                '<select id="page-no-select" class="custom-select">';
        for (var i = 1; i <= pageCount; i++) {
            html = html + '<option value="' + i + '"' +
                    (i === currentPage ? ' selected' : '') + '>' + i +
                    '</option>';
        }
        html = html + '</select></div>';
        $('#pagination-bar').html(html);
        $('#pagination-bar').data('page-size', defaultPageSize);
    };

    window.addPaginationHandlers = function () {
        $('#pagination-bar').on('click', 'a.page-link', function () {
            var $pagination = $(this).closest('.pagination');
            var pageCount = $pagination.data('page-count');
            var currentPage = $pagination.data('page');
            var page = $(this).data('page');
            if (page === -1) {
                page = 1;
            } else if (page === -4) {
                page = pageCount;
            } else if (page === -2) {
                page = Math.max(currentPage - 1, 1);
            } else if (page === -3) {
                page = Math.min(currentPage + 1, pageCount);
            }
            $('#pagination-bar').trigger('pageChange', page);
        });

        $('#pagination-bar').on('change', '#page-no-select', function () {
            var page = $('#page-no-select').val();
            $('#pagination-bar').trigger('pageChange', page, defaultPageSize);
        });
    };

    window.showTab = function (index) {
        var $tabPane = $('#data-modal .tab-pane').eq(index);
        var $tab = $('#tabs a[href="#' + $tabPane.prop('id') + '"]');
        $tab.tab('show');
    };

    window.setModalClosable = function ($modal, closable) {
        $modal.data('closable', (closable ? 1 : 0));
        $modal.find('.modal-header button').prop('disabled', !closable);
        $modal.find('.modal-footer .cancel-button').prop('disabled', !closable);
        $modal.find('form fieldset').prop('disabled', !closable);
        if ($modal.find('#tabs').length > 0 &&
                $modal.find('#tabs').data('initialized') != 1) {
            $modal.find('#tabs').data('initialized', 1);
            $modal.find('#tabs li a').on('show.bs.tab', function(e) {
                if ($(this).closest('.modal').data('closable') === 0) {
                    e.preventDefault();
                }
            });
        }
    }

    window.createAlert = function (className, text) {
        var html = '<div class="alert alert-dismissible show fade">' +
                '<span class="alert-text"></span>' +
                '<button type="button" class="close" data-dismiss="alert">' +
                '<span>&times;</span>' +
                '</button>' +
                '</div>';
        var $alert = $(html);
        $alert.addClass(className);
        $alert.find('.alert-text').text(text);
        return $alert;
    };

    window.loadingButton = function ($button, loading) {
        var html = '';
        var width = 0;
        if (loading) {
            html = $button.html();
            width = $button.width();
            $button.addClass('loading');
            $button.data('button-content', html);
            $button.data('button-width', width);
            html = '<i class="fa fa-spin fa-spinner"></i>';
        } else {
            $button.removeClass('loading');
            html = $button.data('button-content');
            width = $button.data('button-width');
        }
        $button.html(html);
        $button.width(width);
    };

    window.showFormData = function ($form, data) {
        var $dataItems = $form.find('.data-item');
        $.each($dataItems, function (index, element) {
            var $dataItem = $(element);
            if ($dataItem.prop('name')) {
                var tagName = $dataItem[0].tagName;
                var name = $dataItem.prop('name');
                if (name in data) {
                    var value = data[name];
                    if (tagName === 'INPUT') {
                        if ($dataItem.prop('type') === 'checkbox') {
                            $dataItem.prop('checked', value);
                        } else {
                            $dataItem.val(value);
                        }
                    } else if (tagName === 'TEXTAREA') {
                        $dataItem.val(value);
                    }
                }
            }
        });
    };

    window.createAlert = function (className, text) {
        var html = '<div class="alert alert-dismissible show fade">' +
                '<span class="alert-text"></span>' +
                '<button type="button" class="close" data-dismiss="alert">' +
                '<span>&times;</span>' +
                '</button>' +
                '</div>';
        var $alert = $(html);
        $alert.addClass(className);
        $alert.find('.alert-text').text(text);
        return $alert;
    };

    window.showLoadingBox = function (message, minDuration, cancel, callback) {
        var $loadingBox = $('#loading-box');
        if ($loadingBox.length === 0) {
            $(document.body).append($(
                '<div id="loading-box" class="modal fade" tabindex="-1">' +
                    '<div class="modal-dialog modal-sm">' +
                        '<div class="modal-content loading-content">' +
                            '<i class="fa fa-spin fa-spinner"></i>' +
                            '<span class="loading-text"></span>' +
                        '</div>' +
                    '</div>' +
                '</div>'
            ));
            $loadingBox = $('#loading-box');
            $loadingBox.data('timeout-id', 0);
            $loadingBox.data('min-duration', 0);
            $loadingBox.data('showing-start-time', 0);
        }
        var timeoutId = $loadingBox.data('timeout-id');
        if (timeoutId > 0) {
            $loadingBox.data('timeout-id', 0);
            clearTimeout(timeoutId);
        }
        if (isNaN(minDuration)) minDuration = 0;
        minDuration = (isNaN(minDuration) ? 0 : minDuration);
        minDuration = Math.max(minDuration, 500);
        $loadingBox.data('min-duration', minDuration);
        $loadingBox.data('showing-start-time', new Date().getTime());
        $loadingBox.find('.loading-text').html(message);
        if (cancel) $loadingBox.off('hidden.bs.modal');
        if (typeof(callback) === 'function') {
            $loadingBox.one('hidden.bs.modal', function () {
                callback();
            });
        }
        if (!$loadingBox.hasClass('show')) {
            $loadingBox.modal({backdrop: 'static', keyboard: false});
        }
    };

    window.hideLoadingBox = function (callback) {
        var $loadingBox = $('#loading-box');
        if ($loadingBox.length === 0) {
            if (typeof(callback) === 'function') {
                callback();
            }
            return;
        }

        if (typeof(callback) === 'function') {
            if (!$loadingBox.hasClass('show')
                    && $loadingBox.data('showing-start-time') <= 0) {
                callback();
                return;
            } else {
                $loadingBox.off('hidden.bs.modal');
                $loadingBox.one('hidden.bs.modal', function() {
                    callback();
                });
            }
        }

        var timeoutId = $loadingBox.data('timeout-id');
        var minDuration = $loadingBox.data('min-duration');
        var startTime = $loadingBox.data('showing-start-time');
        if (timeoutId > 0) {
            $loadingBox.data('timeout-id', 0);
            clearTimeout(timeoutId);
        }
        if (minDuration <= 0) {
            if ($loadingBox.hasClass('show')) {
                $loadingBox.data('showing-start-time', 0);
                window.forceHideLoadingBox();
            }
            return;
        }

        var now = new Date().getTime();
        var milliseconds = minDuration - (now - startTime);
        if (milliseconds <= 0) {
            if ($loadingBox.hasClass('show')) {
                $loadingBox.data('showing-start-time', 0);
                window.forceHideLoadingBox();
                return;
            }
        }

        timeoutId = setTimeout(function () {
            clearTimeout(timeoutId);
            $loadingBox.data('timeout-id', 0);
            if ($loadingBox.is(':visible')) {
                $loadingBox.data('showing-start-time', 0);
                window.forceHideLoadingBox();
            }
        }, Math.max(milliseconds, 30));
        $loadingBox.data('timeout-id', timeoutId);
    };

    window.forceHideLoadingBox = function () {
        var $loadingBox = $('#loading-box');
        if ($loadingBox.length === 0) return;
        if (!$loadingBox.hasClass('show')) return;
        $loadingBox.modal('hide');
        var timeoutId = setTimeout(function () {
            clearTimeout(timeoutId);
            if ($loadingBox.hasClass('show')) window.forceHideLoadingBox();
        }, 30);
    };

    window.showInformationAlert = function (icon, message, title, callback) {
        var $informationAlert = $('#information-alert');
        if ($informationAlert.length === 0) {
            $(document.body).append($(
                '<div id="information-alert" class="modal fade modal-alert" tabindex="-1">' +
                    '<div class="modal-dialog">' +
                        '<div class="modal-content">' +
                            '<div class="modal-header">' +
                                '<p class="modal-title">提示信息</p>' +
                                '<button type="button" data-dismiss="modal" class="close">' +
                                    '<span>&times;</span>' +
                                '</button>' +
                            '</div>' +
                            '<div class="modal-body">' +
                                '<i class="fa modal-icon"></i>' +
                                '<p class="alert-text"></p>' +
                            '</div>' +
                            '<div class="modal-footer">' +
                                '<button class="btn" data-dismiss="modal">确定</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>'
            ));
            $informationAlert = $('#information-alert');
        }

        var $alertIcon = $informationAlert.find('.modal-icon');
        var $alertText = $informationAlert.find('.alert-text');
        var $alertButton = $informationAlert.find('.btn');
        var $alertTitle = $informationAlert.find('.modal-title');
        var iconFlag = true;
        $alertIcon.removeClass('fa-info-circle');
        $alertIcon.removeClass('fa-exclamation-circle');
        $alertIcon.removeClass('fa-question-circle');
        $alertIcon.removeClass('fa-times-circle');
        $alertButton.removeClass('btn-secondary');
        $alertButton.removeClass('btn-primary');
        $alertButton.removeClass('btn-info');
        $alertButton.removeClass('btn-warning');
        $alertButton.removeClass('btn-danger');
        switch (icon) {
        case 0:
            $alertIcon.addClass('fa-info-circle');
            $alertButton.addClass('btn-primary');
            break;
        case 1:
            $alertIcon.addClass('fa-exclamation-circle');
            $alertButton.addClass('btn-warning');
            break;
        case 2:
            $alertIcon.addClass('fa-question-circle');
            $alertButton.addClass('btn-info');
            break;
        case 3:
            $alertIcon.addClass('fa-times-circle');
            $alertButton.addClass('btn-danger');
            break;
        default:
            $alertButton.addClass('btn-secondary');
            iconFlag = false;
            break;
        }

        if (iconFlag) {
            $alertIcon.show();
        } else {
            $alertIcon.hide();
        }
        $alertText.html(message);
        title = $.trim(title);
        $alertTitle.text(title === '' ? '提示信息' : title);
        if (typeof(callback) === 'function') {
            $informationAlert.one('hidden.bs.modal', callback);
        }
        $informationAlert.modal({keyboard: true});
    }

    window.showQuestionAlert = function (icon, message, title, buttonText, callback) {
        var $questionAlert = $('#question-alert');
        if ($questionAlert.length === 0) {
            $(document.body).append($(
                '<div id="question-alert" class="modal fade modal-alert" tabindex="-1">' +
                    '<div class="modal-dialog">' +
                        '<div class="modal-content">' +
                            '<div class="modal-header">' +
                                '<p class="modal-title">提示信息</p>' +
                                '<button type="button" data-dismiss="modal" class="close">' +
                                    '<span>&times;</span>' +
                                '</button>' +
                            '</div>' +
                            '<div class="modal-body">' +
                                '<i class="fa modal-icon"></i>' +
                                '<p class="alert-text"></p>' +
                            '</div>' +
                            '<div class="modal-footer">' +
                                '<button class="btn btn-secondary cancel-button" data-dismiss="modal">取消</button>' +
                                '<button class="btn btn-primary confirm-button" data-dismiss="modal">确定</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>'
            ));
            $questionAlert = $('#question-alert');
            $questionAlert.find('.confirm-button').click(function () {
                $questionAlert.data('question-alert-confirm', 1);
            });
        }

        var $alertIcon = $questionAlert.find('.modal-icon');
        var $alertText = $questionAlert.find('.alert-text');
        var $confirmButton = $questionAlert.find('.confirm-button');
        var $cancelButton = $questionAlert.find('.cancel-button');
        var $alertTitle = $questionAlert.find('.modal-title');
        var iconFlag = true;
        $alertIcon.removeClass('fa-info-circle');
        $alertIcon.removeClass('fa-exclamation-circle');
        $alertIcon.removeClass('fa-question-circle');
        $alertIcon.removeClass('fa-times-circle');
        $confirmButton.removeClass('btn-primary');
        $confirmButton.removeClass('btn-danger');
        if (icon >= 10) {
            $confirmButton.addClass('btn-danger');
        } else {
            $confirmButton.addClass('btn-primary');
        }
        icon = (icon >= 10 ? icon - 10: icon);
        switch (icon) {
        case 0:
            $alertIcon.addClass('fa-info-circle');
            break;
        case 1:
            $alertIcon.addClass('fa-exclamation-circle');
            break;
        case 2:
            $alertIcon.addClass('fa-question-circle');
            break;
        case 3:
            $alertIcon.addClass('fa-times-circle');
            break;
        default:
            $alertButton.addClass('btn-secondary');
            iconFlag = false;
            break;
        }

        if (iconFlag) {
            $alertIcon.show();
        } else {
            $alertIcon.hide();
        }
        $alertText.html(message);
        title = $.trim(title);
        $alertTitle.text(title === '' ? '提示信息' : title);
        buttonText = $.trim(buttonText);
        if (buttonText) {
            var textList = buttonText.split(',');
            if ($.trim(textList[0])) {
                $confirmButton.text($.trim(textList[0]));
            } else {
                $confirmButton.text('确定');
            }
            if (textList.length > 1 && $.trim(textList[1])) {
                $cancelButton.text($.trim(textList[1]));
            } else {
                $cancelButton.text('取消');
            }
        } else {
            $confirmButton.text('确定');
            $cancelButton.text('取消');
        }

        $questionAlert.data('question-alert-confirm', 0);
        if (typeof(callback) === 'function') {
            $questionAlert.one('hidden.bs.modal', function () {
                if ($questionAlert.data('question-alert-confirm') === 1) {
                    callback();
                }
            });
        }
        $questionAlert.modal({backdrop: 'static', keyboard: false});
    };

    window.showModalWarningAlert = function (message, delay) {
        var $alert = window.createAlert('alert-warning', message);
        $('#data-modal .modal-body .alert').alert('close');
        $('#data-modal .modal-body').append($alert);
        if (delay > 0) {
            var timeoutId = setTimeout(function () {
                clearTimeout(timeoutId);
                $alert.alert('close');
            }, delay);
        }
    };

    window.setFocusTo = function ($target, delay) {
        if (delay > 0) {
            var timeoutId = setTimeout(function () {
                clearTimeout(timeoutId);
                $target.focus();
            }, delay);
        } else {
            $target.focus();
        }
    };

    $('.page-content .card-footer a').click(function () {
        $('html,body').animate({scrollTop: 0}, 500);
    });

    $('input').prop('autocomplete', 'off');
    $('[data-toggle="popover"]').popover();
    window.datetimePicker($('#search-form .date-picker'));

    if ($('#pagination-bar').length > 0) {
        window.showPaginationBar(1, 1);
        window.addPaginationHandlers();
    }

    if ($('#search-form').length > 0) {
        $('#search-form [name="pageNumber"]').val(0);
        $('#search-form [name="pageSize"]').val(defaultPageSize);
        $('#search-form').on('keydown', function (e) {
            if (e.originalEvent.keyCode === 13) {
                e.originalEvent.cancelBubble = true;
                e.originalEvent.stopPropagation();
                e.originalEvent.preventDefault();
                $('#search-form').find('#submit-button').trigger('click');
            }
        });
    }

    $.ajaxSetup({
        beforeSend: function (request) {
            request.setRequestHeader($('meta[name="csrf-parm"]').attr('content') || 'csrfToken',
                    $('meta[name="csrf-token"]').attr('content') || '');
        },
        error: function () {
            hideLoadingBox(function () {
                var modals = $('.modal');
                for (var i = 0, count = modals.length; i < count; i++) {
                    $(modals[i]).modal('hide');
                }
                window.showQuestionAlert(13, '系统产生异常。', '', '重新加载,取消', function () {
                    window.location.reload();
                });
            });
        }
    });
});
